   package com.unuibi.myphone; // 修改为你的包名

   import android.Manifest;
   import android.annotation.TargetApi;
   import android.app.AlertDialog;
   import android.content.DialogInterface;
   import android.content.Intent;
   import android.content.SharedPreferences;
   import android.content.pm.PackageManager;
   import android.graphics.Bitmap;
   import android.graphics.BitmapFactory;
   import android.net.Uri;
   import android.os.Build;
   import android.os.Bundle;
   import android.os.Environment;
   import android.provider.MediaStore;
   import android.text.InputType;
   import android.view.LayoutInflater;
   import android.view.View;
   import android.widget.Button;
   import android.widget.EditText;
   import android.widget.ImageView;
   import android.widget.Toast;

   import androidx.annotation.NonNull;
   import androidx.appcompat.app.AppCompatActivity;

   import java.io.File;
   import java.io.FileOutputStream;
   import java.io.IOException;
   import java.io.InputStream;
   import java.io.OutputStream;
   import java.util.HashMap;
   import java.util.Map;
   import androidx.core.content.ContextCompat;
   import androidx.core.app.ActivityCompat;

   import util.StringUtils;

   public class SecondActivity extends AppCompatActivity {
       private static final int REQUEST_IMAGE_PICK = 2;
       private static final int REQUEST_CALL_PHONE = 1; // 或者任何其他未使用的整数值
       private EditText editTextPhoneNumberDialog;
       private Button buttonSavePhoneNumber;

       private ImageView imageView;
       private String imgName = "imgName_0";
       private String phoneNumber_0;
       private Map<String, String> map = new HashMap<>();
       @Override
       protected void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);
           //加载页面部署视图
           setContentView(R.layout.activity_second);
           // 尝试加载上次保存的图片(如果添加过图片返回true，如果没有添加图片返回false)

           // 设置图片点击事件
           imageView = findViewById(R.id.image_view);
           imageView.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   // 图片点击事件的处理逻辑
                   // 例如，可以在这里添加一个Toast提示
                   if(null!=map && !map.isEmpty()&&"1".equals(map.get(imgName))){
                       String phoneNum =  getPhoneNumber();
                       if(StringUtils.isNotBlank(phoneNum)){
                           dophone(phoneNum);
                       }else {
                           Toast.makeText(SecondActivity.this, "请先添加手机号", Toast.LENGTH_SHORT).show();
                       }
                   }else {
                       openGallery();
                   }
               }
           });
           // 添加长按事件监听器
           imageView.setOnLongClickListener(new View.OnLongClickListener() {
               @Override
               public boolean onLongClick(View v) {
                   // 长按事件的处理逻辑
                   // 显示对话框让用户选择修改图片或手机号
                   showModifyDialog();
                   return true; // 返回true表示事件已经被消费
               }
           });

           loadSavedImage(imgName, imageView);
       }

       @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
           super.onActivityResult(requestCode, resultCode, data);
           if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
               Uri imageUri = data.getData();
               try {
                   saveImageFromUri(imageUri,imgName);
                   loadSavedImage(imgName, imageView); // 加载刚保存的图片
                   String phoneNum =  getPhoneNumber();
                   if(!StringUtils.isNotBlank(phoneNum)){
                       showPhoneNumberDialog();
                   }
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }

       @TargetApi(Build.VERSION_CODES.M)
       private void dophone(String phoneNum) {
           Intent intent = new Intent(Intent.ACTION_CALL);
           Uri data = Uri.parse("tel:" + phoneNum);
           intent.setData(data);
           if (PackageManager.PERMISSION_GRANTED==checkSelfPermission(Manifest.permission.CALL_PHONE)) {
               startActivity(intent);
           } else {
               requestPermission(Manifest.permission.CALL_PHONE);
           }
       }


       @Override
       public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
           super.onRequestPermissionsResult(requestCode, permissions, grantResults);
           if (requestCode == REQUEST_IMAGE_PICK) {
               if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   // 权限被授予，现在可以安全地打开图库
                   openGallery();
               } else {
                   // 权限被拒绝，处理这种情况
                   Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
               }
           }
       }

       private void openGallery() {
           Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
           startActivityForResult(intent, REQUEST_IMAGE_PICK);
       }

       private void saveImageFromUri(Uri uri,String imgName) throws IOException {
           InputStream inputStream = getContentResolver().openInputStream(uri);
           Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

           File dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
           if (!dir.exists()) {
               dir.mkdirs();
           }
           File file = new File(dir, imgName);
           String imagePath = file.getAbsolutePath();

           OutputStream outputStream = new FileOutputStream(file);
           bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
           outputStream.flush();
           outputStream.close();
           inputStream.close();
       }

       /**
        * 载入图片时，如果载入成功返回true，如果载入失败返回false
        * @param imgName
        * @param imageView
        * @return
        */
       private void loadSavedImage(String imgName,ImageView imageView) {
           File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), imgName);
           if (file.exists()) {
               Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
               imageView.setImageBitmap(bitmap);
               map.put(imgName,"1");
           }
       }

       private void showPhoneNumberDialog() {
           AlertDialog.Builder builder = new AlertDialog.Builder(this);
           LayoutInflater inflater = this.getLayoutInflater();
           View dialogView = inflater.inflate(R.layout.dialog_phone_number, null);

           editTextPhoneNumberDialog = dialogView.findViewById(R.id.edit_text_phone_number_dialog);
           buttonSavePhoneNumber = dialogView.findViewById(R.id.button_save_phone_number);

           builder.setView(dialogView)
                   .setTitle("输入手机号码");

           final AlertDialog alertDialog = builder.create();
           alertDialog.show();

           buttonSavePhoneNumber.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   String phoneNumber = editTextPhoneNumberDialog.getText().toString();
                   saveAndDisplayPhoneNumber(phoneNumber);
                   alertDialog.dismiss();
               }
           });
       }

       private void saveAndDisplayPhoneNumber(String phoneNumber) {
           // 保存手机号码的逻辑
           SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
           SharedPreferences.Editor editor = sharedPreferences.edit();
           editor.putString(phoneNumber_0, phoneNumber);
           editor.apply();

           // 显示保存成功的Toast消息
           Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
       }

       private String getPhoneNumber() {
           try{
               SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
               String phoneNumber = sharedPreferences.getString(phoneNumber_0, "");
               return phoneNumber;
           }catch (Exception e){
               System.out.println(e);
           }
           return null;
       }


       // 检查权限
       public int checkSelfPermission(String permission) {
           return ContextCompat.checkSelfPermission(this, permission);
       }

       // 请求权限
       public void requestPermission(String permission) {
           ActivityCompat.requestPermissions(this, new String[]{permission}, REQUEST_CALL_PHONE);
       }


       // 假设的显示对话框方法
       private void showModifyDialog() {
           AlertDialog.Builder builder = new AlertDialog.Builder(this);
           builder.setTitle("请选择");
           String[] items = {"修改图片", "修改手机号"};
           builder.setItems(items, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   switch (which) {
                       case 0:
                           // 修改图片的逻辑
                           openGallery();
                           break;
                       case 1:
                           if(null!=map && !map.isEmpty()&&"1".equals(map.get(imgName))){
                               // 修改手机号的逻辑
                               showPhoneNumberInputDialog();
                           }else {
                               Toast.makeText(SecondActivity.this, "请先添加图片再添加手机号", Toast.LENGTH_SHORT).show();
                           }

                           break;
                   }
               }
           });
           builder.create().show();
       }

       // 假设的显示输入手机号对话框的方法
       private void showPhoneNumberInputDialog() {
           final EditText input = new EditText(this);
           input.setInputType(InputType.TYPE_CLASS_PHONE); // 设置输入类型为电话号码
           AlertDialog.Builder builder = new AlertDialog.Builder(this );
           builder.setTitle("请输入手机号");
           builder.setView(input);
           builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   String newPhoneNumber = input.getText().toString();
                   // 保存新手机号的逻辑
                   saveAndDisplayPhoneNumber(newPhoneNumber);
               }
           });
           builder.setNegativeButton("取消", null);
           builder.create().show();
       }
   }
   